import requests
import re
from notify import send  # 导入青龙通知模块
##cron: 35 7 * * *
##new Env("qfg")
def sign_in(cookies):
    url = "http://qfg360.xyz/plugin.php?id=dc_signin:sign"
    
    headers = {
        "Host": "qfg360.xyz",
        "Proxy-Connection": "keep-alive",
        "Cache-Control": "max-age=0",
        "Origin": "http://qfg360.xyz",
        "Content-Type": "application/x-www-form-urlencoded",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.200 Mobile Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Referer": "http://qfg360.xyz/plugin.php?id=dc_signin:sign&mobile=2",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    
    data = {
        "formhash": "7015e89f",
        "signsubmit": "yes",
        "handlekey": "signin",
        "emotid": "14",
        "referer": "http%3A%2F%2Fqfg360.xyz%2Fplugin.php%3Fid%3Ddc_signin%3Asign",
        "content": "%E6%93%8D%E4%B8%80%E6%93%8D%EF%BC%8C%E5%8D%81%E5%B9%B4%E5%B0%91",
        "signpn": "true"
    }

    try:
        res = requests.post(url, headers=headers, cookies=cookies, data=data)
        
        # 解析签到结果
        if "签到成功" in res.text:
            print("签到状态: 签到成功")
            
            # 提取奖励信息
            reward_match = re.search(r'签到成功~随机奖励(\w+)(\d+)', res.text)
            if reward_match:
                reward_type = reward_match.group(1)  # 奖励类型，如"金币"
                reward_amount = reward_match.group(2)  # 奖励数量
                print(f"获得奖励: {reward_amount} {reward_type}")
                return {
                    "status": "success", 
                    "message": "签到成功",
                    "reward_type": reward_type,
                    "reward_amount": reward_amount
                }
            else:
                print("签到成功，但无法解析奖励信息")
                return {"status": "success", "message": "签到成功"}
                
        elif "您今日已经签过到" in res.text:
            print("签到状态: 今日已签到")
            return {"status": "already_signed", "message": "今日已签到"}
            
        elif "需要先登录" in res.text or "未登录" in res.text:
            print("签到状态: 未登录或Cookie失效")
            return {"status": "not_logged_in", "message": "未登录或Cookie失效"}
            
        else:
            print("签到状态: 未知结果")
            return {"status": "unknown", "message": "未知结果"}
            
    except Exception as e:
        print(f"签到请求失败: {e}")
        return {"status": "error", "message": f"请求失败: {e}"}

# 完整的自动化脚本，包含登录和签到
def auto_login_and_sign(username, password):
    print("=== 开始执行自动登录签到 ===")
    
    # 定义通知标题
    notification_title = "qfg签到通知"
    
    # 首先执行登录
    login_result = simple_login(username, password)
    
    if login_result and login_result.get("status") == "success":
        print("✓ 登录成功")
        username = login_result.get("username", "未知用户")
        usergroup = login_result.get("usergroup", "未知用户组")
        uid = login_result.get("uid", "未知UID")
        
        print(f"用户信息: {username} ({usergroup}), UID: {uid}")
        print("开始执行签到...")
        
        # 在实际应用中，这里应该使用登录后获取的真实cookies
        # 由于我们无法直接获取登录后的cookies，这里需要您手动提供有效的签到cookies
        sign_cookies = {
            "FeKa_2132_saltkey": "C855hyEc",
            "FeKa_2132_lastvisit": "1761711151",
            "FeKa_2132_ulastactivity": "343bHD3A5aMaC8dqSrKV8ThzTapegJeNQ5A0bLFITp0s426FzCVK",
            "FeKa_2132_auth": "a6dbNaff8o5t4KPShyIYf6cdz6HpgWPyAQLCsEin4TmH0velie6UdF%2BefwoheUW0hmbCMbzdw%2Fya8lmvgX08cZsisA",
            "FeKa_2132_lastcheckfeed": "21642%7C1761714771",
            "FeKa_2132_checkpm": "1",
            "FeKa_2132_sid": "iWv56p",
            "FeKa_2132_lip": "104.23.166.87%2C1761714771",
            "FeKa_2132_st_t": "21642%7C1761714783%7C112be507119e96c65814a2ed31d99bde",
            "FeKa_2132_forum_lastvisit": "D_119_1761714783",
            "FeKa_2132_visitedfid": "119",
            "FeKa_2132_lastact": "1761714796%09plugin.php%09",
        }
        
        # 执行签到
        sign_result = sign_in(sign_cookies)
        
        # 构建通知消息
        notification_message = f"登录状态: 成功\n用户: {username}\n签到状态: {sign_result.get('message')}"
        if sign_result.get('reward_amount'):
            notification_message += f"\n获得奖励: {sign_result.get('reward_amount')} {sign_result.get('reward_type')}"
        
        # 发送通知
        try:
            send(notification_title, notification_message)
            print("✓ 通知发送成功")
        except Exception as e:
            print(f"通知发送失败: {e}")
        
        print("=== 执行结果汇总 ===")
        print(f"登录状态: 成功")
        print(f"签到状态: {sign_result.get('status')}")
        if sign_result.get('reward_amount'):
            print(f"获得奖励: {sign_result.get('reward_amount')} {sign_result.get('reward_type')}")
            
        return {
            "login_status": "success",
            "sign_status": sign_result,
            "user_info": {
                "username": username,
                "usergroup": usergroup,
                "uid": uid
            }
        }
    else:
        print("✗ 登录失败")
        # 登录失败也发送通知
        notification_message = "登录失败，请检查账号密码或网络连接"
        try:
            send(notification_title, notification_message)
            print("✓ 通知发送成功")
        except Exception as e:
            print(f"通知发送失败: {e}")
            
        return {
            "login_status": "failed",
            "sign_status": "not_attempted"
        }

# 登录函数（保持不变）
def simple_login(username, password):
    url = "https://qfg360.xyz/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LAtAW&handlekey=loginform&inajax=1"
    
    cookies = {
        "FeKa_2132_saltkey": "Y3bgmjNG",
        "FeKa_2132_lastvisit": "1760457453", 
        "FeKa_2132_seccode": "28435.476907f53f327b9ccc",
        "FeKa_2132_sid": "vKwntN",
        "FeKa_2132_lastact": "1760461190%09member.php%09logging",
    }

    headers = {
        "x-requested-with": "XMLHttpRequest",
        "user-agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.200 Mobile Safari/537.36",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "origin": "https://qfg360.xyz",
        "referer": "https://qfg360.xyz/member.php?mod=logging&action=login&mobile=2",
    }
    
    data = {
        "formhash": "669d692e",
        "referer": "https%3A%2F%2Fqfg360.xyz%2Fmember.php%3Fmod%3Dregister%26mobile%3D2",
        "fastloginfield": "username", 
        "cookietime": "2592000",
        "username": username,
        "password": password,
        "questionid": "0",
        "answer": ""
    }

    res = requests.post(url, headers=headers, cookies=cookies, data=data)
    
    # 检查登录结果并提取用户信息
    if "欢迎您回来" in res.text:
        # 提取用户信息
        match = re.search(r"'username':'([^']+)','usergroup':'([^']+)','uid':'([^']+)'", res.text)
        if match:
            username = match.group(1)
            usergroup = match.group(2)
            uid = match.group(3)
            return {
                "status": "success",
                "username": username,
                "usergroup": usergroup,
                "uid": uid
            }
        else:
            return {"status": "success", "details": "无法解析用户信息"}
    else:
        return {"status": "failed"}

# 使用示例
if __name__ == "__main__":
    username = "lukasi"  # 替换为您的邮箱
    password = "135319"        # 替换为您的密码
    
    result = auto_login_and_sign(username, password)
    print(f"完整执行结果: {result}")